package com.css.dzj.dzjap.modules.lawenforcesuper.service.impl;

import com.css.dzj.dzjap.common.util.Constant;
import com.css.dzj.dzjap.common.util.R;
import com.css.dzj.dzjap.common.util.RandomUtil;
import com.css.dzj.dzjap.modules.executorinfo.dao.ExecutorInfoDao;
import com.css.dzj.dzjap.modules.executorinfo.entity.ApExecutorInfoEntity;
import com.css.dzj.dzjap.modules.executorinfo.service.ExecutorInfoService;
import com.css.dzj.dzjap.modules.lawenforcesuper.entity.*;
import com.css.dzj.dzjap.modules.lawenforcesuper.mapper.ApExtractLawerMapper;
import com.css.dzj.dzjap.modules.lawenforcesuper.mapper.ExtractLawerRelationMapper;
import com.css.dzj.dzjap.modules.lawenforcesuper.service.ApExpertExtractLawerService;
import com.querydsl.core.QueryResults;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 监管专家抽取执法人员service
 */
@Service
public class ApExpertExtractLawerServiceImpl implements ApExpertExtractLawerService {

    @Autowired
    private ApExtractLawerMapper apExtractLawerMapper;

    @Autowired
    private ExecutorInfoService executorInfoService;

    @Autowired
    private ExtractLawerRelationMapper extractLawerRelationMapper;

    @Autowired
    private ExecutorInfoDao executorInfoDao;

    @Autowired
    private JPAQueryFactory jpaQueryFactory;

    /**
     * 抽取执法人员
     * @param apExtractLawerEntity
     * @return
     */
    @Transactional
    @Override
    public R extractLawer(ApExtractLawerEntity apExtractLawerEntity, HttpServletRequest request) {
        try {
            apExtractLawerEntity.setCreateTime(new Date());
            apExtractLawerEntity.setCreatePerson("");
            apExtractLawerEntity.setDelFlag(Constant.NO_DELETE);
            apExtractLawerEntity.setId(UUID.randomUUID().toString());

            apExtractLawerMapper.save(apExtractLawerEntity);

            // 最终抽取的总数
            int randomNum = 0;
            // 向上取整的数量
            int upNum = 0;
            // 需要抽取的国家级执法人员数量
            Integer countryNum = 0;
            // 需要抽取的省级执法人员数量
            Integer provinceNum = 0;
            // 需要抽取的地市级执法人员数量
            Integer cityNum = 0;


            double countryDouble = apExtractLawerEntity.getCountryRatio()/100.0*apExtractLawerEntity.getExtractNum();
            Integer countryInt = Integer.valueOf(new BigDecimal(countryDouble).setScale(0,BigDecimal.ROUND_HALF_DOWN).toString());
            if(upNum == 0) {
                countryNum = Integer.valueOf(new BigDecimal(countryDouble).setScale(0,BigDecimal.ROUND_HALF_UP).toString());
            } else {
                countryNum = countryInt;
            }
            if(countryDouble - countryInt == 0.5) {
                upNum++;
            }

            double provinceDouble = apExtractLawerEntity.getProvinceRatio()/100.0*apExtractLawerEntity.getExtractNum();
            int provinceInt = Integer.valueOf(new BigDecimal(provinceDouble).setScale(0 , BigDecimal.ROUND_HALF_DOWN ).toString());
            if(upNum == 0) {
                provinceNum = Integer.valueOf(new BigDecimal(provinceDouble).setScale(0 , BigDecimal.ROUND_HALF_UP ).toString());
            } else {
                provinceNum = provinceInt;
            }
            if(provinceDouble - provinceInt == 0.5) {
                upNum++;
            }

            cityNum = apExtractLawerEntity.getExtractNum() - countryNum - provinceNum;


            /**
             * 所有国家级执法人员列表
             */
            List<ApExecutorInfoEntity> countryList = executorInfoService.findExecutorByExecutorLevel(Constant.STATE_LEVEL, request);
            // 国际级需抽取的执法人员人数小于等于所有国家执法人员或者所有国家级执法人员的列表为null并且需要抽取的执法人员为0
            if((countryList != null && countryNum <= countryList.size()) || (countryList == null && countryNum == 0)) {
                if(countryList.size() > 0) {
                    List<ApExecutorInfoEntity> apExecutorInfoEntityList = RandomUtil.ramdonExtract(countryList, countryNum.toString());
                    if(apExecutorInfoEntityList.size() > 0) {
                        for (ApExecutorInfoEntity apExecutorInfoEntity : apExecutorInfoEntityList) {
                            ExtractLawerRelationEntity lawerRelationEntity = new ExtractLawerRelationEntity();
                            lawerRelationEntity.setExtractId(apExtractLawerEntity.getId());
                            lawerRelationEntity.setRelateId(apExecutorInfoEntity.getId());
                            lawerRelationEntity.setCreateTime(new Date());
                            lawerRelationEntity.setCreatePerson("");
                            extractLawerRelationMapper.save(lawerRelationEntity);
                            randomNum++;
                        }
                    }

                }
            } else {
                throw new RuntimeException("国家级执法人员不足！");
            }
            /**
             * 所有的省级执法人员列表
             */
            List<ApExecutorInfoEntity> provinceList = executorInfoService.findExecutorByExecutorLevel(Constant.PROVIENCE_LEVEL, request);
            if((provinceList != null && provinceNum <= provinceList.size()) || (provinceList == null && provinceNum == 0)) {
                if(provinceList.size() > 0) {
                    List<ApExecutorInfoEntity> apExecutorInfoEntityList = RandomUtil.ramdonExtract(provinceList, provinceNum.toString());
                    if(apExecutorInfoEntityList.size() > 0) {
                        for (ApExecutorInfoEntity apExecutorInfoEntity : apExecutorInfoEntityList) {
                            ExtractLawerRelationEntity lawerRelationEntity = new ExtractLawerRelationEntity();
                            lawerRelationEntity.setExtractId(apExtractLawerEntity.getId());
                            lawerRelationEntity.setRelateId(apExecutorInfoEntity.getId());
                            lawerRelationEntity.setCreateTime(new Date());
                            lawerRelationEntity.setCreatePerson("");
                            extractLawerRelationMapper.save(lawerRelationEntity);
                            randomNum++;
                        }
                    }
                }

            } else {
                throw new RuntimeException("省级执法人员不足!");
            }

            /**
             * 所有的地市级执法人员列表
             */
            List<ApExecutorInfoEntity> cityList = executorInfoService.findExecutorByExecutorLevel(Constant.CITY_LEVEL, request);
            if((cityList != null && cityNum <= cityList.size()) || (cityList == null && cityNum == 0)) {
                if(cityList.size() > 0) {
                    List<ApExecutorInfoEntity> apExecutorInfoEntityList = RandomUtil.ramdonExtract(cityList, cityNum.toString());
                    if(apExecutorInfoEntityList.size() > 0) {
                        for (ApExecutorInfoEntity apExecutorInfoEntity : apExecutorInfoEntityList) {
                            ExtractLawerRelationEntity lawerRelationEntity = new ExtractLawerRelationEntity();
                            lawerRelationEntity.setExtractId(apExtractLawerEntity.getId());
                            lawerRelationEntity.setRelateId(apExecutorInfoEntity.getId());
                            lawerRelationEntity.setCreateTime(new Date());
                            lawerRelationEntity.setCreatePerson("");
                            extractLawerRelationMapper.save(lawerRelationEntity);
                            randomNum++;
                        }
                    }
                }
            } else {
                throw new RuntimeException("地市级执法人员不足！");
            }

            if(randomNum != apExtractLawerEntity.getExtractNum()) {
                throw new RuntimeException("抽取数量不正确!");
            }

            QExpregulatConnectExpertEntity qConnectExpert = QExpregulatConnectExpertEntity.expregulatConnectExpertEntity;
           jpaQueryFactory.update(qConnectExpert).set(qConnectExpert.cqStatus, Constant.EXTRACT).where(
                   qConnectExpert.regulatId.eq(apExtractLawerEntity.getTaskId()), qConnectExpert.expertId.eq(apExtractLawerEntity.getLinkId()))
                   .execute();

            return R.ok();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }

    }


    /**
     * 通过专家监管任务id和专家id查询执法人员
     * @param pageable
     * @param taskId
     * @param expertId
     * @return
     */
    @Override
    public QueryResults<ApExecutorInfoEntity> queryLawerByTaskIdAndExpertId(Pageable pageable, String taskId, String expertId) {
        List<ApExecutorInfoEntity> apExecutorInfoEntityList = new ArrayList<>();
        ApExtractLawerEntity apExtractLawerEntity = queryByTaskIdAndExpertId(taskId, expertId);
        QueryResults<ExtractLawerRelationEntity> lawerRelationQueryResults = new QueryResults<>(new ArrayList<>(), (long) pageable.getPageSize(), pageable.getOffset(), 0);
        if(apExtractLawerEntity != null) {
            lawerRelationQueryResults = queryByExtractId(pageable, apExtractLawerEntity.getId());
            List<ExtractLawerRelationEntity> lawerRelationEntityList = lawerRelationQueryResults.getResults();
            if(lawerRelationEntityList != null && lawerRelationEntityList.size() > 0 ) {
                for(ExtractLawerRelationEntity lawerRelationEntity : lawerRelationEntityList) {
                    ApExecutorInfoEntity apExecutorInfoEntity = executorInfoDao.findById(lawerRelationEntity.getRelateId()).get();
                    if(!StringUtils.isEmpty(apExecutorInfoEntity)) {
                        apExecutorInfoEntityList.add(apExecutorInfoEntity);
                    }
                }

            }

        }
        QueryResults<ApExecutorInfoEntity> executorQueryResults = new QueryResults<>(apExecutorInfoEntityList, (long)pageable.getPageSize(), pageable.getOffset(), lawerRelationQueryResults.getTotal());
        return executorQueryResults;
    }

    /**
     * 通过taskId和专家id查询执法人员抽取表
     * @param taskId
     * @param expertId
     * @return
     */
    @Override
    public ApExtractLawerEntity queryByTaskIdAndExpertId(String taskId, String expertId) {
        QApExtractLawerEntity qApExtractLawerEntity = QApExtractLawerEntity.apExtractLawerEntity;
        ApExtractLawerEntity extractLawerEntity = jpaQueryFactory.selectFrom(qApExtractLawerEntity).where(qApExtractLawerEntity.taskId.eq(taskId),
                qApExtractLawerEntity.linkId.eq(expertId)).fetchOne();

        return extractLawerEntity;
    }

    /**
     * 通过执法人员抽取表id查询关联列表
     * @param extractId
     * @return
     */
    @Override
    public QueryResults<ExtractLawerRelationEntity> queryByExtractId(Pageable pageable, String extractId) {
        QExtractLawerRelationEntity qExtractLawerRelationEntity = QExtractLawerRelationEntity.extractLawerRelationEntity;
        return jpaQueryFactory.selectFrom(qExtractLawerRelationEntity).where(qExtractLawerRelationEntity.extractId.eq(extractId))
                .orderBy(qExtractLawerRelationEntity.createTime.desc())
                .offset(pageable.getOffset())
                .limit(pageable.getPageSize())
                .fetchResults();
    }
}
